import type { AxiosRequestConfig, AxiosResponse } from "axios";
import Request from "./request";
import type { RequestConfig } from "./request/types";

const ENV = import.meta.env;

export interface fetchResponse<T> {
  statusCode: number;
  desc: string;
  result: T;
}

// 重写返回类型
interface fetchRequestConfig<T, R> extends RequestConfig<R> {
  data?: T;
  name?: string;
}

const request = new Request({
  baseURL: ENV.VITE_BASE_URL as string,
  timeout: 1000 * 60 * 5, // 超时时间 5分钟
  interceptors: {
    // 请求拦截器
    requestInterceptors: (requestConfig: AxiosRequestConfig) => requestConfig,
    // 响应拦截器
    responseInterceptors: (result: AxiosResponse) => {
      return result;
    },
  },
});

/**
 * @description: 函数的描述
 * @generic D 请求参数
 * @generic T 响应结构
 * @param {fetchRequestConfig} config 不管是GET还是POST请求都使用params
 * @returns {Promise}
 */
const fetch = <T = any, D = any>(requestConfig: fetchRequestConfig<T, D>) => {
  const { method = "get" } = requestConfig;
  const configInfo = { ...requestConfig };
  if (method === "put" || method === "post") {
    configInfo.data = requestConfig.params;
    configInfo.params = null;
  }
  return request.request<T>(configInfo);
};

// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return request.cancelRequest(url);
};

// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest();
};

export default fetch;
